package com.zm.demo.core.concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2019/6/18 18:53
 */
public class SemaphoreDemo {

    public static void main(String[]args) throws Exception{
        Semaphore semaphore = new Semaphore(5);
        ExecutorService executorService = Executors.newCachedThreadPool();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        for (int i = 0; i < 20; i++) {
            try {
                semaphore.acquire();
                executorService.submit(() -> {
                    try {
                        out.println(sdf.format(new Date())+ ",阻塞.");
                        Thread.sleep(3000L);
                        out.println(sdf.format(new Date()) + ",释放锁.");
                    } catch (Exception e){
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                });
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        executorService.awaitTermination(30, TimeUnit.SECONDS);
        out.println(sdf.format(new Date())+ ",主线程结束.");
//        executorService.shutdown();

    }
}
